﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Repository;
using Estimate.Common.Entity;

namespace Estimate.Common.DataImporter
{
    /// <summary>
    /// 降水等值线预报数据文件导入
    /// </summary>
    public class RainForeImporter : IDataImporter
    {
        /// <summary>
        /// 存储 站点;值 数组。其中键值是 span和factor合并成的字符串
        /// </summary>
        protected Dictionary<string, List<string>> processedData;

        /// <summary>
        /// 数据库访问类
        /// </summary>
        protected ForeRepository rainForeRepository;

        public RainForeImporter(ForeRepository repository)
        {
            rainForeRepository = repository;
            processedData = new Dictionary<string, List<string>>();
        }

        /// <summary>
        /// 由文件名获取发报时刻
        /// </summary>
        public ForeClockType getClockByFileName(string filename)
        {
            string strClock= filename.Substring(6,2);
            if(strClock == "08")
                return ForeClockType.H08;
            else
                return ForeClockType.H20;
        }

        public DateTime getDateByFileFirstLine(string line)
        {
            int index = line.IndexOf("年");
            int year = 2000 + Convert.ToInt32(line.Substring(index-2,2));
            int month = Convert.ToInt32(line.Substring(index+1,2));
            int day = Convert.ToInt32(line.Substring(index+4,2));
            return new DateTime(year,month,day);
        }

        /// <summary>
        /// 根据给定的参数，判断出ForeSpanType的值类型
        /// </summary>
        /// <param name="hours">小时数</param>
        /// <param name="is12Hours">是否是12小时制</param>
        /// <param name="isFirst">是否是前半截</param>
        /// <returns>ForeSpanType的值</returns>
        private ForeSpanType getForespanFromString(string hours)
        {
            switch (hours)
            {
                case "012":
                    return ForeSpanType.FD00_12;
                case "021":
                    return ForeSpanType.FD12_24;
                case "024":
                    return ForeSpanType.FD00_24;
                case "048":
                    return ForeSpanType.FD24_48;
                case "072":
                    return ForeSpanType.FD48_72;
                case "096":
                    return ForeSpanType.FD72_96;
                case "120":
                    return ForeSpanType.FD96_120;
                case "144":
                    return ForeSpanType.FD120_144;
                case "168":
                    return ForeSpanType.FD144_168;
                default:
                    return ForeSpanType.FD00_12;
            }
        }

        public void ImportDataFromFile(string filepath)
        {
            StreamReader file = new StreamReader(filepath, Encoding.Default);

            string line = file.ReadLine();
            //根据第一行内容，查出生成报告的日期
            DateTime date = getDateByFileFirstLine(line);
            ImportDataFromFileWithDate(filepath, date);            
        }


        public void ImportDataFromFileWithDate(string filepath, DateTime dt)
        {
            //根据文件名获取clock和span参数
            string filename = Path.GetFileName(filepath);
            ForeClockType clock = getClockByFileName(filename);
            ForeSendpointType sendpoint = clock == ForeClockType.H08 ? ForeSendpointType.H06 : ForeSendpointType.H16;
            string strSpan = filename.Substring(filename.IndexOf('.') + 1);
            ForeSpanType span = getForespanFromString(strSpan);

            string st;
            int r1;

            StreamReader file = new StreamReader(filepath, Encoding.Default);

            string line = file.ReadLine();

            line = file.ReadLine();

            List<string> values = new List<string>();
            do
            {
                line = file.ReadLine();
            } while (line.Trim() != "STATION_SITUATION");

            line = file.ReadLine();
            while (line.Substring(0, 14) != "WEATHER_REGION")
            {
                string pattern = @"\ +";
                string[] foreserial = Regex.Split(line, pattern, RegexOptions.IgnoreCase);

                st = foreserial[0];
                r1 = (int)Convert.ToSingle(foreserial[1]);
                values.Add(string.Format("{0};{1}", st, r1.ToString()));
                line = file.ReadLine();
            }

            if (values.Count > 0)
            {
                ForeEntity entity = new ForeEntity();
                entity.Date = dt;
                entity.Clock = clock;
                entity.Sendpoint = sendpoint;
                entity.Semitype = ForeSemiType.Auto;
                entity.Span = span;
                entity.Type = ForeFactorType.wth;
                entity.Value = string.Join("|", values.ToArray());
                entity.Semi = "";
                if (DataWillBeSaved(entity))
                {
                    rainForeRepository.SetForeRecord(entity);
                }
            }
        }


        /// <summary>
        /// 未实现该事件。目前用不到
        /// </summary>
        public event EventHandler AfterDataInDatabase;



        public event EventHandler BeforeDataInDatabase;

        /// <summary>
        /// 在保存数据前引发 BeforeDataInDatabase 信号
        /// 并将参数中是否入库的变量返回
        /// </summary>
        /// <param name="score">即将入库的数据</param>
        /// <returns>是否入库。 true则表示将入库。 false则表示不会入库</returns>
        public bool DataWillBeSaved(ForeEntity entity)
        {
            object data = entity.Clone();
            if (BeforeDataInDatabase != null)
            {
                FindDataEventArgs args = new FindDataEventArgs(data);
                BeforeDataInDatabase(this, args);
                return args.SaveData;
            }
            return true;
        }
    }
}
